<template>
  <div>
    <el-form class="query-form"
      ref="queryForm"
      size="small"
      :model="queryParams"
      :inline="true">
      <el-form-item label="订单所属项目" prop="app_id" class="big-query">
        <select-check-box v-model="queryParams.app_ids"
         :props="{value: 'app_id', label: 'name'}"
          :selOptions="permission_projectList"
          checkAllLabel="全部项目"/>
      </el-form-item>
      <el-form-item label="版本" prop="version" placeholder="请输入">
        <el-input v-model="queryParams.version" placeholder="用,分割版本"/>
      </el-form-item>
      <el-form-item label="渠道" prop="channel_id" class="big-query">
        <select-check-box :filterable="true"  v-model="queryParams.channel_array"
         :props="{ value: 'channel_id', label: 'name'}"
          :selOptions="channelOptions"
          @change="handleQuery"
          checkAllLabel="全部渠道"/>
      </el-form-item>
      <el-form-item label="订单类型" prop="product_type" placeholder="请输入">
        <el-select v-model="queryParams.product_type"
          placeholder="请选择"
          @change="handleQuery">
          <el-option
            label="全部"
            :value="null"/>
          <el-option
            label="权益包"
            :value="2" />
          <el-option
            label="AI绘图"
            :value="4" />
          <el-option
            label="捐赠"
            :value="5" />
          <el-option
            label="加购包"
            :value="6" />
        </el-select>
      </el-form-item>
      <el-form-item label="加购包"
        v-if="queryParams.product_type===6"
        prop="attr_id">
        <el-select v-model="queryParams.attr_id2"
          placeholder="请选择"
          @change="handleQuery">
          <el-option
            label="全部"
            :value="null"/>
          <el-option v-for="item in rightPackageOptions" :key="item.id"
            :label="item.name"
            :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="权益包"
        v-else
        prop="attr_id">
        <el-select v-model="queryParams.attr_id1"
          placeholder="请选择">
          <el-option
            label="全部"
            :value="null"/>
          <el-option v-for="item in packageList" :key="item.package_id"
            :label="item.name"
            :value="item.package_id" />
        </el-select>
        <!-- <select-check-box  v-model="queryParams.attr_id1"
            :selOptions="packageList"
            :props="{value:'package_id',label:'name'}"
            checkAllLabel="全部">
        </select-check-box> -->
      </el-form-item>

      <el-form-item label="支付方式" prop="pay_type" class="small-query">
        <el-select v-model="queryParams.pay_type" placeholder="请选择" @change="handleQuery">
          <el-option label="全部" :value="null"/>
          <el-option v-for="item in payTypeOptions" :key="item.dictValue"
            :label="item.dictLabel"
            :value="item.dictValue" />
        </el-select>
      </el-form-item>
      <el-form-item label="支付入口" prop="pay_entry" class="small-query">
        <el-select v-model="queryParams.pay_entry" placeholder="请选择" @change="handleQuery">
          <el-option label="全部" :value="null"/>
          <el-option v-for="item in payEntryOptions" :key="item.dictValue"
            :label="item.dictLabel"
            :value="item.dictValue" />
        </el-select>
      </el-form-item>
      <el-form-item label="订单状态"
        prop="status"
        class="">
        <select-check-box v-model="queryParams.status_array"
         :props="{value: 'id', label: 'label'}"
          :selOptions="orderStatusOptions"
          @change="handleQuery"
          checkAllLabel="全部状态"/>
      </el-form-item>
      <el-form-item label="试用状态"
        prop="trial_status"
        class="small-query">
        <el-select v-model="queryParams.trial_status"
          placeholder="请选择"
          @change="handleQuery">
          <el-option key="all"
            label="全部"
            :value="null"/>
          <el-option label="已试用" :value="1"></el-option>
          <el-option label="未试用" :value="2"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="订单金额">
        <el-input-number v-model="numberRange.pay_amount_begin"
          placeholder="最低价"
          size="small"
          :precision="2"
          style="width: 83px"/>
        -
        <el-input-number v-model="numberRange.pay_amount_end"
          placeholder="最高价"
          size="small"
          :precision="2"
          style="width: 83px"/>
      </el-form-item>
      <el-form-item label="加购价">
        <el-input-number v-model="numberRange.add_price_begin"
          placeholder="最低价"
          size="small"
          :precision="2"
          style="width: 83px"/>
        -
        <el-input-number v-model="numberRange.add_price_end"
          placeholder="最高价"
          size="small"
          :precision="2"
          style="width: 83px"/>
      </el-form-item>
      <el-form-item label="订单周期" prop="payCycle" class="small-query">
        <el-select v-model="queryParams.payCycle"
          placeholder="请选择"
          @change="handleQuery">
          <el-option
            label="全部"
            :value="null"/>
          <el-option
            label="1天"
            :value="1" />
          <el-option
            label="1-7天"
            :value="2" />
          <el-option
            label="7天+"
            :value="3" />
        </el-select>
      </el-form-item>
      <el-form-item class="big-query" label="创建订单时间" prop="createDateRange">
        <template slot="label">
          <p class="suffix__label">
            <span>创建订单时间</span>
            <span>(仅针对已付款订单)</span>
          </p>
        </template>
        <el-date-picker v-model="queryParams.createDateRange"
          type="daterange"
          value-format="yyyy-MM-dd"
          range-separator="~"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          @change="handleQuery">
        </el-date-picker>
      </el-form-item>
      <el-form-item class="big-query" label="支付时间">
        <el-date-picker v-model="payDateRange"
          type="daterange"
          value-format="yyyy-MM-dd"
          range-separator="~"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          @change="handleQuery">
        </el-date-picker>
      </el-form-item>
      <el-form-item class="big-query" >
        <template slot="label">
          <p class="suffix__label">
            <span>退款创建时间</span>
            <span>(仅针对已退款订单)</span>
          </p>
        </template>
        <el-date-picker v-model="queryParams.refundDateRange"
          type="daterange"
          value-format="yyyy-MM-dd"
          range-separator="~"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          @change="handleQuery">
        </el-date-picker>
      </el-form-item>
      <el-form-item class="small-query" label="关键词"
        prop="keyword">
        <el-select v-model="queryParams.search_field"
          @change="handleChangeKeywordType"
          :style="{ marginRight: '5px' }">
          <el-option label="订单号" value="order_id"/>
          <el-option label="用户ID" value="user_id"></el-option>
          <el-option label="手机号" value="user_phone"></el-option>
        </el-select>
        <el-input v-model="queryParams.keyword"
          :placeholder="keywordPlaceholder"
          size="small"
          style="width:240px"
          clearable
          @keyup.enter.native="handleQuery"
          @clear="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary"
          size="small"
          @click="handleQuery">搜索</el-button>
        <el-button
          size="small"
          @click="resetQuery">重置</el-button>
        <el-button
          size="small"
          type="success"
          :loading="exportLoading"
          @click="exportExcel">导出全部</el-button>
      </el-form-item>
    </el-form>
    <div class="text-right">
      <el-popover
        placement="bottom-end"
        popper-class="table-check_popover"
        width="560"
        trigger="click">
        <div>
          <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">字段选择</el-checkbox>
          <hr/>
          <el-checkbox-group v-model="checkList" @change="handleCheckedChange">
            <div>
              <span class="table-check_label">订单信息：</span>
              <el-checkbox label="user_id">用户ID</el-checkbox>
              <el-checkbox label="user_nick">用户昵称</el-checkbox>
              <el-checkbox label="user_phone">注册账号</el-checkbox>
              <el-checkbox label="channel_id">下单渠道</el-checkbox>
            </div>
            <div class="mt10" style="padding-left: 70px;">
              <el-checkbox label="pay_type">支付方式</el-checkbox>
              <el-checkbox label="pay_entry">支付入口</el-checkbox>
              <el-checkbox label="product_name">订单名称</el-checkbox>
              <el-checkbox label="pay_price">订单金额</el-checkbox>
              <el-checkbox label="add_price">加购价</el-checkbox>
              <el-checkbox label="refund_amount">退款金额</el-checkbox>
            </div>
            <div class="mt10" style="padding-left: 70px;">
              <el-checkbox label="create_time">创建订单时间</el-checkbox>
              <el-checkbox label="pay_time">支付订单时间</el-checkbox>
              <el-checkbox label="refund_at">退款创建时间</el-checkbox>
              <el-checkbox label="pay_cycle">订单周期</el-checkbox>
            </div>
            <div class="mt10" style="padding-left: 70px;">
              <el-checkbox label="agreement_status">签约状态</el-checkbox>
              <el-checkbox label="signed_at">签约时间</el-checkbox>
              <el-checkbox label="unsigned_at">解约时间</el-checkbox>
            </div>
          </el-checkbox-group>
        </div>
        <el-button type="text" slot="reference">字段选择<i class="el-icon-arrow-down"></i></el-button>
      </el-popover>
    </div>
    <el-table v-loading="loading"
      style="margin-bottom: 15px;"
      @sort-change="onSortChange"
      :data="orderList">
      <!-- 新增 -->
      <el-table-column label="父订单号"
        min-width="200"
        prop="parent_order_no" />
      <el-table-column label="用户ID"
        min-width="100"
        prop="user_id"
        v-if="checkList.includes('user_id')">
        <template  #default="{ row }">
          <el-button size="small" type="text" @click="handleUserDetail(row)">{{row.user_id}}</el-button>
        </template>
      </el-table-column>
      <el-table-column label="注册账号"
        width="120"
        prop="reg_account"
        v-if="checkList.includes('user_phone')"/>
      <el-table-column label="用户昵称"
        width="110"
        show-overflow-tooltip=""
        prop="user_nick"
        v-if="checkList.includes('user_nick')"/>
      <el-table-column label="下单渠道"
        width="120"
        prop="channel_id"
        v-if="checkList.includes('channel_id')">
         <template #default="{ row }">
          <span>{{ row.channel_id |  translateToName(channelOptions, 'channel_id', 'name')}}</span>
        </template>
      </el-table-column>
      <el-table-column label="下单区域"
        width="110"
        show-overflow-tooltip=""
        prop="country"/>
      <el-table-column label="订单所属项目"
        width="120">
        <template slot-scope="scope">
          <span>{{ scope.row.app_id|translateToName(permission_projectList,'app_id','name') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="版本"
        width="120"
        prop="version"/>
      <el-table-column label="支付方式"
        width="100"
        prop="pay_type"
        v-if="checkList.includes('pay_type')">
        <template slot-scope="scope">
          <el-tag :type="scope.row.pay_type === 2 ? 'success':scope.row.pay_type === 1?'' :'info'"
            disable-transitions>{{ typeFormat(scope.row) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="支付入口"
        width="100"
        prop="pay_entry"
        v-if="checkList.includes('pay_entry')">
        <template slot-scope="scope">
          <span>{{ payEntryFormat(scope.row) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="订单名称"
        min-width="170"
        prop="product_name"
        v-if="checkList.includes('product_name')"/>
      <el-table-column label="订单金额"
        width="100"
        prop="pay_price"
        sortable="custom"
        v-if="checkList.includes('pay_price')">
        <template #default = {row}>
          {{ row.currency_code | formatMoneyCode }}{{ row.pay_price | formatMoney}}
        </template>
      </el-table-column>
      <el-table-column label="加购价"
        width="100"
        prop="add_price"
        sortable="custom"
        v-if="checkList.includes('add_price')">
        <template #default = {row}>
          {{ row.currency_code | formatMoneyCode }}{{ row.add_price | formatMoney}}
        </template>
      </el-table-column>
      <el-table-column label="退款金额"
        width="100"
        prop="refund_amount"
        v-if="checkList.includes('refund_amount')">
        <template #default = {row}>
          <span v-if="row.refund_amount">{{ row.currency_code | formatMoneyCode }}{{ row.refund_amount | formatMoney}}</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="创建订单时间"
        min-width="160"
        show-overflow-tooltip
        prop="create_time"
        v-if="checkList.includes('create_time')"/>
      <el-table-column label="支付订单时间"
        min-width="160"
        show-overflow-tooltip
        prop="pay_time"
        sortable="custom"
        v-if="checkList.includes('pay_time')"/>
      <el-table-column label="退款创建时间"
        min-width="160"
        show-overflow-tooltip
        prop="refund_at"
        v-if="checkList.includes('refund_at')"/>
      <el-table-column label="订单周期" width="100" v-if="checkList.includes('pay_cycle')">
        <template slot-scope="scope">
          {{ scope.row.pay_cycle|payCycleFilter }}
        </template>
      </el-table-column>
      <el-table-column label="试用状态"
        min-width="80">
        <template #default = {row}>
          <el-tag :type="row.trial_status===1? 'success' : 'danger'" disable-transitions>
            {{ row.trial_status===1 ? '已试用' : '未试用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="订单状态" width="100">
        <template slot-scope="scope">
          <el-tag :type="orderStatus.get(scope.row.status).tagType"
            disable-transitions>{{ orderStatus.get(scope.row.status).desc }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="签约状态"
        min-width="80" v-if="checkList.includes('agreement_status')">
        <template #default = {row}>
          <template v-if="agreeOrderStatus.get(row.agreement_status)">
            <el-tag :type="agreeOrderStatus.get(row.agreement_status).tagType" disable-transitions>
              {{ agreeOrderStatus.get(row.agreement_status).desc }}
            </el-tag>
          </template>
        </template>
      </el-table-column>
      <el-table-column label="签约时间"
        min-width="160"
        show-overflow-tooltip
        prop="signed_at"
        v-if="checkList.includes('signed_at')"/>
      <el-table-column label="解约时间"
        min-width="160"
        show-overflow-tooltip
        prop="unsigned_at"
        v-if="checkList.includes('unsigned_at')"/>
      <el-table-column label="操作"
        fixed="right"
        :width="toolbarWidth"
        class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="small" type="text" :disabled="scope.row.status!==2||!!scope.row.related_parent_order_id" @click="handleRefund(scope.row)">退款</el-button>
          <el-button size="small" type="text" @click="handleDetail(scope.row)">详情</el-button>
          <template v-if="showInvoicePayTypes.includes(scope.row.pay_type)">
            <el-button size="small" type="text" v-if="![0,5,6].includes(scope.row.invoice_status)||scope.row.status!==2||!!scope.row.related_parent_order_id" disabled>开票</el-button>
            <el-button size="small" type="text" v-else @click="handleInvoice(scope.row)">开票</el-button>
          </template>
        </template>
      </el-table-column>
    </el-table>
    <p v-for="item in orderAmounts" :key="item.currency_code">
      <span class="span-amount">已付款： {{item.currency_code|formatMoneyCode}} {{item.amount|formatMoney}}</span>
      <span class="span-amount">平均每单 {{item.currency_code|formatMoneyCode}} {{(item.amount/item.count)|formatMoney}}</span>
      <span class="span-amount">已退款： {{item.currency_code|formatMoneyCode}} {{item.refunded_amount|formatMoney}}</span>
      <span class="span-amount">收入 {{item.currency_code|formatMoneyCode}} {{(item.amount-item.refunded_amount)|formatMoney}}</span>
    </p>
    <pagination v-if="total>0"
      :total="total"
      layout="total,slot,sizes,prev,pager,next,jumper"
      :page.sync="queryParams.page"
      :limit.sync="queryParams.page_size"
      @pagination="getList">
    </pagination>
      <!-- 订单详情 -->
      <el-dialog title="订单详情" :visible.sync="open" width="700px" :close-on-click-modal="false">
        <orderDetail :orderInfo="orderInfo" :payTypeOptions="payTypeOptions" :channelOptions="channelOptions" @handleUserDetail="handleUserDetail"/>
      </el-dialog>
    <el-dialog title="用户详情" :visible.sync="userOpen" width="700px" :close-on-click-modal="false" top="5vh">
      <userDetail :userInfo="userInfo" :channelOptions="channelOptions"/>
    </el-dialog>
    <AuthCode ref="AuthCode" :visible.sync="openAuth" :title="authTitle" :authObj="authObj" @submit="submitRefund"/>
    <el-dialog title="退款" :visible.sync="showRefund" width="500px" @closed="reset">
      <el-form
        ref="refundForm"
        size="small"
        :model="refundObj"
        :rules="rules"
        >
        <el-form-item label="订单号：">
          <span>{{refundObj.parent_order_no}}</span>
        </el-form-item>
        <el-form-item label="订单名称："><span>{{refundObj.product_name}}</span></el-form-item>
        <el-form-item label="订单金额："><span>{{refundObj.pay_price | formatMoney}}</span></el-form-item>
        <el-form-item label="退款金额：" prop="refund_amount" class="query-form" :error="refundError">
          <el-input-number v-model="refundObj.refund_amount"
            placeholder=""
            :precision="2"
            style="width: 200px"
            :max="refundObj.pay_price/100"/>
            <el-button type="text" style="margin-left: 20px;" @click="allRefund">全额</el-button>
        </el-form-item>

      </el-form>
      <div slot="footer">
        <el-button type="primary" @click="sendRefundCode">确 定</el-button>
        <el-button @click="showRefund = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 申请发票 -->
    <invoiceDetail :open.sync="openInvoice" openType="add" :row="invoiceInfo" @handleSuccess="getList"/>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import Axios from 'axios'
import AuthCode from '@/components/auth-code'
import userDetail from '@/views/user/components/user-detail.vue'
import { listOrder, getOrder, getGiveOrder, refundOrder, createExportOrderTask, queryExportOrderTask } from '@/api/order/order'
import { getChannelByAppId } from '@/api/system/channel'
import { listRightPackage } from '@/api/rights/package'
import { getPackageList } from '@/api/addition'
import { getUser } from '@/api/user/user'
import { sendCode } from '@/api/member/product'
import { parseTime, downloadExportUrl } from '@/utils'
import storage from '@/utils/storage'
import orderDetail from './components/order-detail.vue'
import { getOrderStatus, getAgreeOrderStatus, getInvoiceStatus } from '@/constants/constant'
import invoiceDetail from '@/views/financial/components/invoice-detail.vue'
const tableOpt = ['user_id', 'user_nick', 'user_phone', 'channel_id', 'pay_type', 'pay_type', 'product_name', 'pay_price', 'add_price', 'refund_amount', 'create_time', 'pay_time', 'refund_at', 'pay_cycle', 'agreement_status', 'unsigned_at']
const noDefault = ['pay_entry', 'signed_at']
export default {
  name: 'Order',
  components: { AuthCode, orderDetail, userDetail, invoiceDetail },
  data () {
    return {
      // 遮罩层
      loading: true,
      // 总条数
      total: 0,
      // 总金额
      orderAmounts: 0,
      // 权益表格数据
      orderList: null,
      // 渠道选择
      channelOptions: [],
      payTypeOptions: [],
      payEntryOptions: [],
      packagesOptions: [],
      rightPackageOptions: [],
      // 是否显示弹出层
      authTitle: '',
      openAuth: false,
      showRefund: false,
      open: false,
      userOpen: false,
      orderStatus: null,
      // 显示开票入口的支付类型
      showInvoicePayTypes: [],
      invoiceStatus: null,
      // 申请开票
      openInvoice: false,
      invoiceInfo: {},
      // 表单参数
      authObj: {},
      orderInfo: {},
      userInfo: {},
      // 查询参数 - 支付时间
      payDateRange: undefined,
      // 查询参数
      queryParams: {
        page: 1,
        page_size: 10,
        product_type: null,
        version: '',
        channel_id: null,
        pay_type: null,
        pay_entry: null,
        attr_id: null,
        attr_id1: null,
        attr_id2: null,
        status_array: [2],
        channel_array: [],
        keyword: '',
        search_field: 'order_id',
        app_ids: [],
        trial_status: null,
        payCycle: null,
        // 查询参数 - 订单创建时间
        createDateRange: null,
        refundDateRange: []
        // member_deadline: 10
      },
      // 查询数字区间参数
      numberRange: {
        pay_amount_begin: undefined,
        pay_amount_end: undefined,
        add_price_begin: undefined,
        add_price_end: undefined
      },
      refundObj: {
        parent_order_no: '',
        pay_price: 0,
        product_name: '',
        refund_amount: undefined
      },
      isIndeterminate: false,
      checkAll: false,
      checkList: [],
      exportLoading: false,
      refundError: '',
      rules: {
        refund_amount: [
          { required: true, message: '金额不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    ...mapGetters('zcsd-core', ['permission_projectList']),
    packageList () {
      if (this.queryParams.app_ids.length) {
        return this.packagesOptions.filter(item => {
          return (item.appids || []).some(item1 => this.queryParams.app_ids.includes(item1))
        })
      }
      return this.packagesOptions
    },
    toolbarWidth () {
      let w = 90
      if (this.showInvoicePayTypes.length) {
        w += 30
      }
      return w
    },
    keywordPlaceholder () {
      const type = this.queryParams.search_field
      switch (type) {
        case 'order_id':
          return '请输入订单号'
        case 'user_id':
          return '请输入用户ID'
        case 'user_phone':
          return '请输入手机号'
        default:
          return '请输入订单号'
      }
    }
  },
  filters: {
    payCycleFilter (val) {
      switch (true) {
        case val > 8:
          return '7天+'
        case val > 1:
          return '1-7天'
        case val === 1:
          return '1天'
        default:
          return ''
      }
    }
  },
  created () {
    const now = parseTime(new Date(), '{y}-{m}-{d}')
    const list = this.permission_projectList.map(item => item.app_id)
    this.queryParams.createDateRange = [now, now]
    // const merchant_id = this.$store.getters['zcsd-core/checkProject'].merchant_id
    // if (['w2083e34d8a987'].includes(merchant_id)) {
    //   // 目前仅翻译的联想支付
    // 目前仅支持联想支付、360支付
    this.showInvoicePayTypes = [5, 8]
    // }
    this.invoiceStatus = getInvoiceStatus()
    this.orderStatus = getOrderStatus()
    this.orderStatusOptions = [...this.orderStatus.keys()].map(v => ({ id: v, label: this.orderStatus.get(v).desc }))
    this.agreeOrderStatus = getAgreeOrderStatus()
    this.checkList = storage.get('orderTable') || [...tableOpt]
    this.handleCheckedChange(this.checkList)
    Axios.all([this.getListApi(), getChannelByAppId({ app_ids: list.join(',') })]).then(Axios.spread((res1, res2) => {
      this.channelOptions = res2.data.list.map(item => ({ name: `${item.name}(${item.channel_id})`, channel_id: item.channel_id }))
      this.orderList = res1
    }))
    this.getDicts('pay_method').then(res => {
      this.payTypeOptions = (res.data || []).map(item => {
        item.dictValue = parseInt(item.dictValue) || 0
        return item
      })
    })
    this.getDicts('pay_entry').then(res => {
      this.payEntryOptions = res.data || []
    })
    this.getDicts('user_account_type').then(res => {
      this.userTypeOptions = res.data || []
    })
    listRightPackage({ page: 1, page_size: 100, status: 10 }).then(res => {
      this.packagesOptions = res.data.list || []
    })
    getPackageList({ page: 1, page_size: 100 }).then(res => {
      this.rightPackageOptions = res.data.list || []
    })
  },
  methods: {
    handleChangeKeywordType () {
      this.queryParams.keyword = ''
      this.handleQuery()
    },
    handleCheckAllChange (val) {
      this.checkList = val ? [...tableOpt, ...noDefault] : []
      this.isIndeterminate = false
      storage.set('orderTable', this.checkList)
    },
    handleCheckedChange (value) {
      let checkedCount = value.length
      const count = tableOpt.length + noDefault.length
      this.checkAll = checkedCount === count
      this.isIndeterminate = checkedCount > 0 && checkedCount < count
      storage.set('orderTable', value)
    },
    getListApi () {
      const params = this.mergeQueryParams()
      this.loading = true
      return new Promise((resolve, reject) => {
        listOrder(params).then(response => {
          const data = response.data || {}
          resolve(data.list)
          this.orderAmounts = data.order_amounts || []
          this.total = data.count || 0
        }).finally(() => {
          this.loading = false
        })
      })
    },
    /** 查询用户列表 */
    getList () {
      this.getListApi().then(res => {
        this.orderList = res
      })
    },
    // 支付方式内置字典翻译
    typeFormat (row, column) {
      return this.selectDictLabel(this.payTypeOptions, row.pay_type)
    },
    // 支付方式内置字典翻译
    payEntryFormat (row, column) {
      return this.selectDictLabel(this.payEntryOptions, row.pay_entry)
    },
    /** 搜索按钮操作 */
    handleQuery () {
      let { queryParams, numberRange } = this
      Object.keys(numberRange).forEach(key => {
        const item = numberRange[key]
        this.queryParams[key] = item ? item * 100 : undefined
      })
      const isPayAmountValid = this.validNumberRangeInput(queryParams, 'pay_amount_begin', 'pay_amount_end')
      const isAddPriceValid = this.validNumberRangeInput(queryParams, 'add_price_begin', 'add_price_end')
      if (!isPayAmountValid || !isAddPriceValid) {
        this.msgError('请检查数字区间输入')
        return
      }
      this.queryParams.page = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery () {
      this.payDateRange = []
      Object.keys(this.numberRange).forEach(key => {
        this.numberRange[key] = undefined
      })
      this.queryParams.refundDateRange = []
      this.resetForm('queryForm')
      // this.queryForm.attr_id1 = null
      // this.queryForm.attr_id2 = null
      this.handleQuery()
    },
    onSortChange ({ prop, order }) {
      this.queryParams.sort_field = order ? prop : null
      this.queryParams.sort_method = order === 'descending' ? 'desc' : 'asc'
      this.getList()
    },
    handleRefund (row) {
      getGiveOrder({ parent_order_id: row.parent_order_no }).then(res => {
        const list = res.data?.list || []
        if (list.length) {
          const h = this.$createElement
          const arr = []
          for (const item of list) {
            arr.push(h('p', null, `订单：${item.parent_order_id}(${item.order_name})`))
          }

          this.$msgbox({
            width: '500px',
            title: '警告',
            message: h('div', null, [
              h('p', null, `订单${row.parent_order_no}为活动关联订单，退款后，以下订单赠送的权益也会同步退款：`),
              h('br'),
              ...arr
            ]),
            showCancelButton: true

          }).then(action => {
            this.showRefundDialog(row)
          })
        } else {
          this.showRefundDialog(row)
        }
      })
      // return
    },
    showRefundDialog (row) {
      this.refundObj.parent_order_no = row.parent_order_no
      this.refundObj.product_name = row.product_name
      this.refundObj.pay_price = row.pay_price
      this.showRefund = true
    },
    reset () {
      this.resetForm('refundForm')
    },
    allRefund () {
      this.$refs.refundForm.clearValidate('refund_amount')
      this.refundObj.refund_amount = parseFloat((this.refundObj.pay_price / 100).toFixed(2))
    },
    sendRefundCode () {
      this.$refs['refundForm'].validate(valid => {
        if (!valid) return
        const amount = Math.round(this.refundObj.refund_amount * 100)
        const orderNo = this.refundObj.parent_order_no
        this.showRefund = false
        this.authObj = {
          type: 'refund',
          data: {
            order_no: orderNo,
            refund_amount: amount
          }
        }
        sendCode(Object.assign({ mock: true }, this.authObj)).then(res => {
          if (res.data.need_verify) {
            this.authTitle = `确定将订单${orderNo}进行退款${parseFloat((this.authObj.data.refund_amount / 100).toFixed(2))}元吗？验证码通过验证后才可进行操作`
            this.openAuth = true
          } else {
            this.submitRefund({
              code: res.data.code,
              vid: res.data.vid
            })
          }
        })
      })
    },
    submitRefund (codeObj) {
      refundOrder({ order_no: this.authObj.data.order_no, refund_amount: this.authObj.data.refund_amount }, codeObj).then(() => {
        this.$message({
          type: 'success',
          message: '退款成功!'
        })
        this.openAuth = false
        this.getList()
      }).catch(e => {
        if (e?.data?.data?.sub_code === 'not_enough') {
          this.$message.closeAll()
          this.handleConfirmRefund({ order_no: this.authObj.order_no }, codeObj)
        }
        this.$refs.AuthCode.cancelLoading()
      })
    },
    handleConfirmRefund (row, codeObj) {
      this.$confirm(`用户剩余智币不足退款，是否进行强制退款`, '强制退款', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        refundOrder({
          order_no: row.order_no,
          force: true
        // eslint-disable-next-line sonarjs/no-identical-functions
        }, codeObj).then(() => {
          this.$message({
            type: 'success',
            message: '退款成功!'
          })
          this.getList()
        })
      })
    },
    /** 查看详情 */
    handleDetail (row) {
      getOrder(row.order_no).then(response => {
        this.orderInfo = response.data
        this.open = true
      })
    },
    userTypeFormat (row, column) {
      return this.selectDictLabel(this.userTypeOptions, row.reg_type)
    },
    /** 查看详情 */
    handleUserDetail (row) {
      // this.loading = true
      getUser(row.auth_id).then(response => {
        const data = response.data
        data.reg_types = this.userTypeFormat(data)
        this.userInfo = data
        this.userOpen = true
      }).finally(() => {
        // this.loading = false
      })
    },
    /** 申请开票 */
    handleInvoice (row) {
      this.invoiceInfo = {
        order_id: row.parent_order_no,
        amount: row.pay_price
      }
      this.openInvoice = true
    },

    /** 点击-全部导出 */
    exportExcel () {
      this.exportLoading = true
      const queryParams = this.mergeQueryParams()
      const params = Object.assign({}, queryParams)
      delete params.page
      delete params.page_size
      createExportOrderTask({ filter: params })
        .then(response => {
          const { task_id } = response.data || {}
          if (task_id) {
            this.queryExportTask(task_id, () => {
              this.exportLoading = false
            })
          } else {
            this.$message.error('导出订单任务创建失败')
            this.exportLoading = false
          }
        })
        .catch(e => {
          this.exportLoading = false
        })
    },
    /** 查询导出订单任务结果 */
    queryExportTask (task_id, func) {
      queryExportOrderTask({ task_id })
        .then(response => {
          if (response.data?.status === 'finished') {
            downloadExportUrl(response.data.file_url)
            typeof func === 'function' && func(true)
          } else {
            setTimeout(() => {
              this.queryExportTask(task_id, func)
            }, 1000)
          }
        })
        .catch(() => {
          typeof func === 'function' && func(false)
        })
    },

    /** 合并列表搜索条件 */
    mergeQueryParams () {
      let queryParams = this.deepClone(this.queryParams)
      let { payDateRange } = this
      const createDate = this.addDateRange(queryParams.createDateRange, 'create_begin', 'create_end')
      const payDate = this.addDateRange(payDateRange, 'pay_begin', 'pay_end')
      const refundDate = this.addDateRange(queryParams.refundDateRange, 'refund_at_begin', 'refund_at_end')
      queryParams.attr_id = queryParams.attr_id1
      if (queryParams.payCycle === 1) {
        queryParams.pay_cycle_end = 1
        queryParams.pay_cycle_begin = 1
      } else if (queryParams.payCycle === 2) {
        queryParams.pay_cycle_end = 7
        queryParams.pay_cycle_begin = 2
      } else if (queryParams.payCycle === 3) {
        queryParams.pay_cycle_end = null
        queryParams.pay_cycle_begin = 8
      } else {
        queryParams.pay_cycle_end = null
        queryParams.pay_cycle_begin = null
      }
      if (queryParams.product_type) {
        if (queryParams.product_type === 6) {
          queryParams.attr_id = queryParams.attr_id2
        }
        queryParams.product_types = [queryParams.product_type]
      } else {
        queryParams.product_types = [2, 4, 5, 6]
      }
      if (queryParams.status_array.length === this.orderStatus.size) {
        queryParams.status_array = []
      }
      if (queryParams.channel_array.length === this.channelOptions.length) {
        queryParams.channel_array = []
      }

      queryParams.keyword = queryParams.keyword.trim()

      Object.assign(queryParams, createDate, payDate, refundDate)
      return queryParams
    },
    handleStatusChange (v) {
      const status = this.queryParams.status_array
      const isAll = status.length === this.orderStatus.size
      this.queryParams.status_array = isAll ? [] : [...this.orderStatus.keys()]
      // if

      // if (this.queryParams.status.includes('all')) {
      //   this.queryParams.status = ['all']
      // }
    }
  }
}
</script>

<style lang="scss" scoped>
.query-form {
  /deep/ .el-select__tags {
    flex-wrap: nowrap;
  }
}
.suffix__label {
  display: flex;
  align-items: center;
  flex-direction: column;
  gap: 4px;
  line-height: 1.2;
  span:nth-of-type(2) {
    font-size: 12px;
    color: rgba($color: #606266, $alpha: 0.7);
  }
}
</style>
